﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Messaging;
using System.Configuration;
using System.Threading;
using TPTecnicas.MessageProcessor.Email.Receiver.MessageProcessorService;
using TPTecnicas.MessageConnection;
using TPTecnicas.MessageProcessor.Common;

namespace TPTecnicas.MessageProcessor.Email.Receiver
{
    partial class EmailReceiver : ServiceBase
    {
        private Thread _reveiverThread;
        private MessageProcessorServiceClient _processorClient;

        public EmailReceiver()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            var reveiveMailsMethod = new ThreadStart(ReceiveMails);
            _reveiverThread = new Thread(reveiveMailsMethod);
            _reveiverThread.Start();

            _processorClient = new MessageProcessorServiceClient();
        }

        private void ReceiveMails()
        {
            while (true)
            {
                try
                {
                    Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["WaitingInterval"]));

					POP3LibraryWrapper obj = new POP3LibraryWrapper();
					//usuario(sin @)
					obj.Connect("pop.gmail.com", "tecnicas.de.diseno.2012", "tecnicas2012");

					Mail mail = Utils.RxMessageToMail(obj.GetLastMail());

					obj.Disconnect();

                    _processorClient.ProcessMessage(new TPTecnicas.MessageProcessor.Common.Message() { });
                }
                catch (Exception ex)
                {
                    continue;
                }
            }
        }

        protected override void OnStop()
        {
           
            try
            {
                _reveiverThread.Abort();
            }
            catch (Exception ex)
            {

            }
        }
    }
}
